package cn.lhn.ridersclub.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

public class EmailSender {

    @Value("${spring.mail.username}")
    private String fromEmail;

    private final JavaMailSender javaMailSender;

    public EmailSender(JavaMailSender javaMailSender) {
        this.javaMailSender = javaMailSender;
    }

    public void sendSimpleMail(String to, String subject, String content) throws RuntimeException {

        try {
            SimpleMailMessage message = new SimpleMailMessage();
            //发件人
            message.setFrom(fromEmail);
            //收件人
            message.setTo(to);
            //邮件主题
            message.setSubject(subject);
            //邮件内容
            message.setText(content);
            //发送邮件
            javaMailSender.send(message);
        }
        catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    public void sendHtmlMail(String to, String subject, String content) throws RuntimeException {
        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper messageHelper;
            messageHelper = new MimeMessageHelper(message, true);
            messageHelper.setFrom(fromEmail);
            messageHelper.setTo(to);
            message.setSubject(subject);
            messageHelper.setText(content, true);
            javaMailSender.send(message);
        }
        catch (MessagingException e) {
            throw new RuntimeException(e.getMessage());
        }
    }
}
